<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <a-card>
            <titleName title="基本信息"></titleName>
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="16" :sm="16">
                                <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                                    <org-tree-select v-model="form.projectId" :disabled="true"  isAutoSelectFirst checkStrictly @select="selectOrg"></org-tree-select>
                                </a-form-model-item>
                        </a-col>
                    <!-- <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属分公司" prop="branchComId">
                            <SelectSubCompany
                                :isDefaultSelected="pageType == 'add'"
                                placeholder="请选择"
                                v-model="form.branchComId"
                                disabled
                            ></SelectSubCompany>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属项目" prop="projectId">
                            <SelectProject
                                :isDefaultSelected="pageType == 'add'"
                                placeholder="请选择"
                                v-model="form.projectId"
                                :form="form"
                                :isClear="id == ''"
                                keyValue="branchComId"
                                disabled
                                @change="change"
                            ></SelectProject>
                        </a-form-model-item>
                    </a-col> -->
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="已返还金额(万元)" prop="returnedAmount">
                            <BaseInputNumber placeholder="请输入" disabled v-model="form.returnedAmount" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="预留风险金(万元)" prop="reservedRiskFund">
                            <BaseInputNumber placeholder="请输入" disabled v-model="form.reservedRiskFund" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="" class="item">
                            本次申请项目部人员风险金返还
                            <a-form-model-item
                                :colon="false"
                                label=" "
                                prop="returnRatio"
                                :style="{ display: 'inline-block' }"
                            >
                                <a-input-number
                                    :min="0"
                                    :disabled="pageType == 'look'"
                                    style="width: 350px; margin-top: -34px"
                                    placeholder="请输入"
                                    v-model="form.returnRatio"
                                />
                            </a-form-model-item>
                            % 。依据《商务管理手册》，项目部已完成（具体事项）：
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" style="margin-left: -130px">
                        <a-form-model-item :colon="false" label=" " class="tx" prop="completedThings">
                            <BaseTextarea
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                                v-model="form.completedThings"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col v-if="pageType != 'look'" :md="24" :sm="24">
                        <a-form-model-item label="附件上传">
                            <upload-list
                                :businessCode="'BM24'"
                                :uploadArrys.sync="form.fileInfoVOList"
                                @fileArrysData="handleFileUploaded"
                                multiple
                            ></upload-list>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" v-else>
                        <a-form-model-item label="附件">
                            <file-link :fileList="form.fileInfoVOList"></file-link>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <a-card v-if="pageType == 'look' && form.financeAudit">
            <titleName title="公司财务资金部"></titleName>
            <a-form-model
                ref="ruleForm1"
                :model="form.financeAudit"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="核定预留风险金(万元)" prop="approveAmount">
                            <BaseInputNumber disabled placeholder="请输入" v-model="form.financeAudit.approveAmount" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="其中，已转抵 (万元)" prop="creditedAmount">
                            <BaseInputNumber disabled placeholder="请输入" v-model="form.financeAudit.creditedAmount" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="本次应返还(万元)" prop="returnAmount">
                            <BaseInputNumber disabled placeholder="请输入" v-model="form.financeAudit.returnAmount" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="审批意见" prop="financeOpinions">
                            <BaseTextarea disabled placeholder="请输入" v-model="form.financeAudit.financeOpinions" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <!--  -->
        <a-card v-if="pageType == 'look' && form.commercialAudit">
            <titleName title="公司商务管理部"></titleName>
            <a-form-model
                ref="ruleForm2"
                :model="form.commercialAudit"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="" class="item">
                            该项目部人员所预留风险金符合《商务管理手册》有关返还条件，建议本次返还预留风险金
                            <a-form-model-item
                                :colon="false"
                                label=" "
                                prop="reserveReturnRatio"
                                :style="{ display: 'inline-block' }"
                            >
                                <a-input-number
                                    disabled
                                    :min="0"
                                    style="width: 250px; margin-top: -34px"
                                    placeholder="请输入"
                                    v-model="form.commercialAudit.reserveReturnRatio"
                                />
                            </a-form-model-item>
                            %
                            <a-form-model-item
                                :colon="false"
                                label=" "
                                prop="reserveReturnAmount"
                                :style="{ display: 'inline-block' }"
                            >
                                <a-input-number
                                    disabled
                                    :min="0"
                                    style="width: 250px; margin-top: -34px"
                                    placeholder="请输入"
                                    v-model="form.commercialAudit.reserveReturnAmount"
                                />
                            </a-form-model-item>
                            （万元）
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="审批意见" prop="commercialOpinions">
                            <BaseTextarea
                                disabled
                                placeholder="请输入"
                                v-model="form.commercialAudit.commercialOpinions"
                            />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <div class="tool-btns page-btn-right-top" v-if="pageType != 'look'">
            <a-button
                v-if="id != '' && form.auditStatus == 'DRAFT'"
                type="danger"
                :loading="loading.DELETE"
                @click="handleSave('DELETE')"
                >删除草稿</a-button
            >
            <a-button
                v-if="form.auditStatus == 'REJECTED'"
                type="primary"
                :loading="loading.REJECTED"
                @click="handleSave('REJECTED')"
                >保存</a-button
            >
            <a-button v-else type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')">保存草稿</a-button>
            <a-button type="primary" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')">提交</a-button>
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
        <div class="tool-btns page-btn-right-top" v-else>
            <BasePrintButton
                type="primary"
                v-if="form.auditStatus == 'PAST'"
                :beforePrintFn="checkProjectRiskReturnPrint"
            />
            <a-button type="primary" class="ml20" @click="handleClose" v-if="checkVisibleInDetail">关闭</a-button>
        </div>
        <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>
import {
    getProjectRiskReturn,
    addProjectRiskReturn,
    editProjectRiskReturn,
    delProjectRiskReturn,
    checkProjectRiskReturn,
    checkProjectRiskReturnPrint,
    checkAddData
} from '@/api/businessAffairs/riskRefund'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectProjectJob from '@/components/Select/SelectProjectJob' // 项目
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import UploadList from '@/components/UploadList'
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        SelectProjectJob,
        UploadList,
        BasePrintButton
    },
    data() {
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: { commercialAudit: null, financeAudit: null, reservedRiskFund: void 0, returnedAmount: void 0,projectId:null},

            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                completedThings: [{ required: true, message: '请输入' }],
                reservedRiskFund: [{ required: true, message: '请输入' }],
                returnedAmount: [{ required: true, message: '请输入' }],
                returnRatio: [{ required: true, message: '请输入' }]
            },
            id: '',

            pageType: '',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            }
        }
    },
    async mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.checkProjectRiskReturnReq()
        }else{
            this.form.projectId = this.$userInfo().currentPost.projectId;
        }
        this.pageType = this.$route.query.pageType
        if (this.pageType == 'look') {
            this.$route.meta.title = '项目风险金返还查看'
        } else {
            this.$route.meta.title = this.id == '' ? '项目风险金返还新增' : '项目风险金返还编辑'
        }
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_project_reserve_risk_fund_return')
    },
    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
                this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName };
                // console.log('this.form.project',this.form.project)
                this.change()
            }
        },
        checkProjectRiskReturnPrint() {
            return checkProjectRiskReturnPrint({ id: this.id }).then((res) => {
                console.log(res)
                return res[1].data.content
            })
        },
        async change() {
            const [err, res] = await checkAddData({ projectId: this.form.projectId })
            if (!err) {
                this.$nextTick(() => {
                    this.form.reservedRiskFund = res.data.reservedRiskFund
                    this.form.returnedAmount = res.data.returnedAmount
                    console.log(this.form)
                })
            }
        },
        async checkProjectRiskReturnReq() {
            const [err, res] = await checkProjectRiskReturn({ id: this.id })
            if (!err) {
                this.form = res.data
            }
        },
        handleFileUploaded(list) {
            this.form.fileInfoVOList = [...list]
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((valid) => {
                flag = valid
               if(!valid) {
                 this.$message.warning("请填写完所有必填项信息")
               }
            })
            return flag
        },
        async delProjectRiskReturn(params) {
            const [err, res] = await delProjectRiskReturn(params)
            if (!err) {
                this.$message.success('成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
            this.setProcessConfig = null;
            if (status != 'DELETE') {
                if (!this.validateForm()) return
                if (isAttachment(this, status, this.form.fileInfoVOList)) return
            }
            if (this.loading[status]) return

            const params = {
                ...this.form,
                auditStatus: status
                // id: this.$route.query.id || void 0,
            }
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? editProjectRiskReturn : addProjectRiskReturn
            const delParams = {id:params.id,type:1}
            const map = {
                DELETE: delProjectRiskReturn,
                DRAFT: fn,
                SUBMITTED: fn,
                REJECTED: fn
            }
            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '关闭',
                    onOk: () => {
                        return that.delProjectRiskReturn(delParams)
                    }
                })
            } else {
                this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
                  if(!flag) {
                    this.loading[status] = false
                    return
                  }
                this.loading[status] = true
                const [err, res] = await map[status](params)
                if (!err) {
                    this.$message.success('成功')
                  if(status =='SUBMITTED') {
                    //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                    }else{
                    this.handleClose()
                }
                }
                  this.loading[status] = false
                })
            }


        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.tx {
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    margin-left: 30px;
}
.return-ratio .ant-form-item-children .ant-form-explain {
    margin-left: 230px;
}
.inputStyl {
    border-color: #e4ac0b;
    background-color: #fff9e8;
}
.item {
    margin-left: 30px;
}
.item .ant-form-item {
    margin-top: -28px;
}
</style>
